//
//  DeviceOrientation.swift
//  PhotoVideo
//
//  Created by 惠 on 2020/9/25.
//

import UIKit
import CoreMotion

class DeviceOrientation: NSObject {
    private let sensitive = 0.77
    
    private let motionManager = CMMotionManager()
    
    private var direction: UIInterfaceOrientation = .portrait
    
    
    // 每隔一个间隔做轮询
    func start() {
        motionManager.deviceMotionUpdateInterval = 0.5
        
        if motionManager.isDeviceMotionAvailable {
            motionManager.startDeviceMotionUpdates(to: OperationQueue.current!) {[weak self] (motion, error) in
                self?.performSelector(onMainThread: #selector(self?.deviceMotion(motion:)), with: motion, waitUntilDone: true)
            }
        }
    }
    
    @objc func deviceMotion(motion: CMDeviceMotion) {
        let x = motion.gravity.x
        let y = motion.gravity.y
        
        if y < 0 {
            if fabs(y) > sensitive {
                if direction != .portrait {
                    direction = .portrait
                    NotificationCenter.default.post(name: UIDevice.orientationDidChangeNotification, object: nil, userInfo: ["direction": direction])
                }
            }
        }else {
            if y > sensitive {
                if direction != .portraitUpsideDown {
                    direction = .portraitUpsideDown
                    NotificationCenter.default.post(name: UIDevice.orientationDidChangeNotification, object: nil, userInfo: ["direction": direction])
                }
            }
        }
        if x < 0 {
            if fabs(x) > sensitive {
                if direction != .landscapeLeft {
                    direction = .landscapeLeft
                    NotificationCenter.default.post(name: UIDevice.orientationDidChangeNotification, object: nil, userInfo: ["direction": direction])
                }
            }
        }else {
            if x > sensitive {
                if direction != .landscapeRight {
                    direction = .landscapeRight
                    NotificationCenter.default.post(name: UIDevice.orientationDidChangeNotification, object: nil, userInfo: ["direction": direction])
                }
            }
        }
    }
    
    func stop() {
        motionManager.stopDeviceMotionUpdates()
    }
    
}
